package com.vonchenchen.renderer;

import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;

/**
 * Created by  on 2021/1/27.
 */
public class CoordinatesTransform {
    public CoordinatesTransform() {
    }

    public static RectF normalizedFaceRect(Rect rect, int displayOrientation, boolean isMirror) {
        Matrix matrix = new Matrix();
        prepareMatrix(matrix, isMirror, displayOrientation);
        RectF rectF = new RectF(rect);
        matrix.mapRect(rectF);
        return rectF;
    }

    private static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation) {
        matrix.setScale(mirror ? -1.0F : 1.0F, 1.0F);
        matrix.postRotate((float)displayOrientation);
        matrix.postScale(5.0E-4F, 5.0E-4F);
        matrix.postTranslate(0.5F, 0.5F);
    }

    public static Rect sensorToNormalizedPreview(Rect transformRect, int previewWidth, int previewHeight, Rect cropRegion) {
        double previewRatio = previewWidth > previewHeight ? (double)previewWidth / (double)previewHeight : (double)previewHeight / (double)previewWidth;
        double cropRatio = (double)cropRegion.width() / (double)cropRegion.height();
        int cropResizeWidth = cropRegion.width();
        int cropResizeHeight = cropRegion.height();
        if (previewRatio > cropRatio) {
            cropResizeHeight = (int)((double)cropResizeWidth / previewRatio);
        } else {
            cropResizeWidth = (int)((double)cropResizeHeight * previewRatio);
        }

        int deltaCropX = Math.abs(cropResizeWidth - cropRegion.width());
        int deltaCropY = Math.abs(cropResizeHeight - cropRegion.height());
        RectF rect = new RectF(transformRect);
        Matrix matrix = new Matrix();
        matrix.postTranslate((float)(-cropRegion.left - deltaCropX / 2), (float)(-cropRegion.top - deltaCropY / 2));
        matrix.postTranslate((float)(-cropResizeWidth / 2), (float)(-cropResizeHeight / 2));
        matrix.postScale(2000.0F / (float)cropResizeWidth, 2000.0F / (float)cropResizeHeight);
        matrix.mapRect(rect);
        Rect resultRect = new Rect();
        rect.round(resultRect);
        return resultRect;
    }
}
